/**
 * Http请求封装工具类
 * Axios是基于http客户端的promise，面向浏览器和NodeJS
 * Created by LinWang on 2018/08/08.
 */
import axios from 'axios'
import qs from 'qs'
import store from '../store'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import _ from 'lodash'
import { showFullScreenLoading, tryHideFullScreenLoading } from './loadService'

/**
 * 创建Axios实例
 */
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: process.env.TIME_OUT
})
service.all = axios.all;
service.spread = axios.spread;

/**
 * 添加一个请求拦截器（前置）
 */
service.interceptors.request.use(
  config => {
    showFullScreenLoading()
    if (config.headers['Content-Type'] !== 'multipart/form-data' && !config.isJson) {
      if (_.isObject(config.data)) {
        config.data = qs.stringify(config.data, { allowDots: true })
      }
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded' // 默认为 application/json
    }
    config.headers.operator = getToken() // 让每个请求携带自定义token，请根据实际情况自行修改
    config.headers.requestId = new Date().getTime() // 请求时间点
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

/**
 * 添加一个返回拦截器（后置处理）
 */
service.interceptors.response.use(
  response => {
    tryHideFullScreenLoading()
    const res = response.data
    if (response.status !== 200 || !res.success) {
      Message({
        message: res.message,
        type: 'warning',
        duration: 5 * 1000
      })
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm(
          '你已被登出，可以取消继续留在该页面，或者重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject(res)
    } else {
      return res.data
    }
  },
  error => {
    tryHideFullScreenLoading()
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'warning',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
